package com.ansion.basedb.dao.impl;

import android.text.TextUtils;

import com.ansion.basedb.dao.DaoLoadHelper;
import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.UserFTSHelper;
import com.ansion.basedb.dao.UserLogicDao;
import com.ansion.basedb.dao.helper.ContactsHelper;
import com.ansion.basedb.dao.helper.UserHelper;
import com.ansion.basedb.dao.model.ContactsModel;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.database.IDatabaseManager;
import com.ansion.basedb.notify.UserChangeNotifier;
import com.ansion.basedb.storage.StorageSdk;
import com.ansion.basedb.util.UserBroadcastUtils;
import com.ansion.log.VLog;
import com.ansion.string.StringUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ValueSafeTransfer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class UserLogicCachedDaoImpl extends UserLogicDaoImpl {
    //	private AtomicBoolean isLoaded = new AtomicBoolean(false);
    private HashMap<Long, UserModel> cachedUserMap = new HashMap<Long, UserModel>();
    private static final String TAG = "TAG_USER_TABLE";
    private boolean isMatchEnd = false;

    @Override
    public void clearCache() {
        isMatchEnd = false;
        if (null != cachedUserMap) {
            cachedUserMap.clear();
        }
        DaoLoadHelper.userDaoLoadFinish = false;
    }

    @Override
    public UserModel getUserByUcid(String ucid) {
        UserModel user = super.getUserByUcid(ucid);
        if (user != null) {
            ContactsModel contact = ContactsHelper.getContact(user.getUserId());
            user.setContact(contact);
        }
        return user;
    }


    @Override
    public UserModel getUser(long uid) {
        UserModel user = null;
        synchronized (this) {
            user = cachedUserMap.get(uid);
        }
        if (null != user) {
            if (!isSystemId(uid)) {
                user.setContact(ContactsHelper.getContact(uid));
//				user.setLastSeenModel(LastSeenHelper.getLastSeenModel(uid));
            }
            return user;
        }
        if (!isLoaded()) {//这行代码与cacheOnly等效，所以getUser不需要cacheOnly
            user = super.getUser(uid);
        }
        if (null == user) {
            ContactsModel contact = ContactsHelper.getContact(uid);
            if (null != contact) {
                user = new UserModel();
                user.setUserId(uid);
                user.setContact(contact);
                user.setBaba(false);
                return user;
            } else {
                user = new UserModel();
                user.setUserId(uid);
                if (!isSystemId(uid)) {
                    user.setBaba(false);
                } else {
                    user.setBaba(true);
                }
                return user;
            }
        }
        if (!isSystemId(uid)) {
            user.setContact(ContactsHelper.getContact(uid));
//			user.setLastSeenModel(LastSeenHelper.getLastSeenModel(uid));
        }
        synchronized (this) {
            cacheUser(user);
            return user;
        }
    }

    @Override
    public UserModel getUserOnly(long uid) {
        UserModel user = null;
        synchronized (this) {
            user = cachedUserMap.get(uid);
        }
        if (null != user) {
            return user;
        }
        if (!isLoaded()) {//这行代码与cacheOnly等效，所以getUser不需要cacheOnly
            user = super.getUser(uid);
        }
        synchronized (this) {
            if (user != null)
                cacheUser(user);

        }
        return user;
    }


    private boolean isSystemId(long uid) {
        return uid == ContactUtil.BOTIM_TEAM_ID || uid == ContactUtil.SOMA_NEWS_ID ||
                uid == ContactUtil.BOTIM_FILE_ASSISTANT_ID ||
                String.valueOf(uid).startsWith(ContactUtil.OA_PREFIX);
    }

    private void cacheUser(UserModel user) {
        user.setBaba(true);
        cachedUserMap.put(user.getUserId(), user);
    }

    @Override
    public List<UserModel> loadAll() {
        synchronized (this) {
            List<UserModel> userList;
            if (DaoLoadHelper.userDaoLoadFinish) {
                userList = new ArrayList<UserModel>();
                for (UserModel user : cachedUserMap.values()) {
                    userList.add(user);
                }
                return userList;
            } else {
                userList = super.loadAll();
                if (userList != null) {
                    for (UserModel user : userList) {
                        cacheUser(user);
                    }
                }
                DaoLoadHelper.userDaoLoadFinish = true;
            }
            return userList;
        }
    }


    @Override
    public void saveUser(UserModel user) {
        synchronized (this) {
            user.setUpdateTime(System.currentTimeMillis());
            if (cachedUserMap.containsKey(user.getUserId())) {
                UserModel tmp = cachedUserMap.get(user.getUserId());
                if (dataHasChange(user, tmp)) {//修复老版本数据比对取反了的问题
                    VLog.i(TAG, "user data has changed:%d", user.getUserId());
                    cacheUser(user);
                    VLog.i(TAG, "replaceUser 0:%d", user.getUserId());
                    super.replaceUser(user, false);
                    return;
                }
                user.setBackground(tmp.getBackground());
                cacheUser(user);
            } else {
                cacheUser(user);
            }
            VLog.i(TAG, "replaceUser 1:%d", user.getUserId());
            super.replaceUser(user);
        }
        UserFTSHelper.indexUser(user);
    }

    private boolean dataHasChange(UserModel user1, UserModel user2) {
        if (StringUtils.stringIsEqual(user1.getAvatarUrl(),
                user2.getAvatarUrl())
                && StringUtils.stringIsEqual(user1.getNickName(),
                user2.getNickName())
                && StringUtils.stringIsEqual(user1.getNote(), user2.getNote())
                && user1.getContactId() == user2.getContactId()
                && user1.getStatus_type() == user2.getStatus_type()
                && StringUtils.stringIsEqual(user1.getCountry(),
                user2.getCountry())
                && StringUtils.stringIsEqual(user1.getCountryPhone(),
                user2.getCountryPhone())
                && user1.isVip() == user2.isVip() && StringUtils.stringIsEqual(user1.getOaIcon(), user2.getOaIcon())
                && user1.isOaVerified() == user2.isOaVerified() && user1.getOaSubType() == user2.getOaSubType()
        ) {
            return false;
        }
        return true;
    }

    @Override
    public void saveUsers(List<UserModel> userList) {

        for (UserModel user : userList) {
            synchronized (this) {
                user.setUpdateTime(System.currentTimeMillis());
                cacheUser(user);
                VLog.i(TAG, "saveUsers %d", user.getUserId());
            }
        }
        super.saveUsers(userList);
    }
//    @Override
//    public void saveGroupUser(List<GroupUserPB> groupUserPB) {
//        if (groupUserPB == null || groupUserPB.size() == 0) {
//            return;
//        }
//
//        List<UserModel> replaceList = new ArrayList<UserModel>();
//        for (GroupUserPB groupUserPb : groupUserPB) {
//            if (groupUserPb == null) {
//                continue;
//            }
//
//
//            // 计算变更后再发通知
//            boolean avatarChange = false;
//            //内存的值已经被修改，这里有问题
//            UserModel tmpUser = cachedUserMap.get(groupUserPb.uid);
//            boolean vipChange = false;
//            String userId = ValueSafeTransfer.stringValue(groupUserPb.uid);
//            Boolean newVip = groupUserPb.isVip;
//            boolean nickNameChange = false;
//            if (tmpUser == null) {
//                avatarChange = !TextUtils.isEmpty(groupUserPb.avatar);
//                if (groupUserPb.isVip != null) {
//                    //从非vip变vip
//                    vipChange = (groupUserPb.isVip == true);
//                }
//                tmpUser = new UserModel();
//
//            } else {
//                //groupUserPb有头像，且头像跟本地的不一样
//                avatarChange = !TextUtils.isEmpty(groupUserPb.avatar) && !StringUtils.stringIsEqual(groupUserPb.avatar, tmpUser.getAvatarUrl());
//                if (groupUserPb.isVip != null) {
//                    vipChange = groupUserPb.isVip != tmpUser.isVip();
//                }
//            }
//            //与老版本保持一致，直接存，不管有没有变更
//            UserModel updateUser = UserHelper.mergeServerUser(tmpUser, groupUserPb);
//            cacheUser(updateUser);
//            replaceList.add(updateUser);
//            VLog.i(TAG, "saveGroupUser for:%d", updateUser.getUserId());
//            if (avatarChange) {
//                UserChangeNotifier.getInstance().notifyAvatarChange(userId, updateUser.getAvatarUrl());
//            }
//            if (vipChange)
//                UserChangeNotifier.getInstance().notifyVipChange(userId, newVip);
//
//        }
//        super.replaceUsers(replaceList);
//    }

//    public List<UserModel> saveUserFromSimpleCocoAccountPBs(
//            List<BabaAccountPB> simpleCocoAccountPBList,
//            UserLogicDao.DBOperationCallback callBack) {
//        IDatabaseManager mainDB = StorageSdk.getMainDB();
//        if (null == mainDB || simpleCocoAccountPBList == null
//                || simpleCocoAccountPBList.size() == 0) {
////			if(!isMatchEnd){
////				isMatchEnd = true;
////				CocoDaoBroadcastUtil.sendUserModelChangeIntent(CocoDaoBroadcastUtil.kDAOCategory_RowReplace, null);
////			}
//            return null;
//        }
//        boolean hasChange = false;
//        List<UserModel> replaceList = new ArrayList<UserModel>();
//        UserModel tmpUser;
//        // 计算变更后再发通知
//
//        for (BabaAccountPB simpleUserPb : simpleCocoAccountPBList) {
//            synchronized (this) {
//                if (simpleUserPb == null)
//                    continue;
//                if ((TextUtils.isEmpty(simpleUserPb.name) || TextUtils.isEmpty(simpleUserPb.avatar)) && ContactUtil.isOAAccount(simpleUserPb.uid)) {
//                    if (VLog.OPEN_LOG)
//                        VLog.e(LogTag.TAG_OA, "accountproxy.getSimpleBabaAccountList get empty name or avatar;uid:" + simpleUserPb.uid);
//                }
//                boolean avatarChange = false;
//                boolean vipChange = false;
//                boolean walletChange = false;
//                boolean oaVerifyChange = false;
//                boolean nameChange = false;
//                Boolean newVip = simpleUserPb.isVip;
//                Boolean newWallet = simpleUserPb.isWallet;
//                boolean isCertified = simpleUserPb.isCertified != null && simpleUserPb.isCertified;
//                String oaIcon = isCertified ? simpleUserPb.certificationIcon : null;
//                String userId = ValueSafeTransfer.stringValue(simpleUserPb.uid);
//                if (cachedUserMap.containsKey(simpleUserPb.uid)) {
//                    UserModel newModel = UserHelper.createUserModelFromPB(simpleUserPb);
//                    tmpUser = cachedUserMap.get(simpleUserPb.uid);
//                    avatarChange = !StringUtils.stringIsEqual(tmpUser.getAvatarUrl(), newModel.getAvatarUrl());
//                    //OaIcon有且跟之前的不一样
//                    oaVerifyChange = !TextUtils.isEmpty(newModel.getOaIcon()) && !StringUtils.stringIsEqual(tmpUser.getOaIcon(), newModel.getOaIcon());
//                    if (newVip != null) {
//                        vipChange = (newVip != tmpUser.isVip());
//                    }
//                    nameChange = !StringUtils.stringIsEqual(tmpUser.getNickName(), newModel.getNickName());
//                    if (newWallet != null) {
//                        walletChange = (newWallet != tmpUser.isBadgeWallet());
//                    }
//                    if (hasChange(newModel, tmpUser) || vipChange || oaVerifyChange || walletChange) {//当内容，vip或者oa认证标识变更的时候
//                        VLog.i(TAG, "saveUserFromSimpleCocoAccountPBs user has changed for %d", simpleUserPb.uid);
//                        hasChange = true;
//                    }
//                    UserModel updateUser = UserHelper.mergeServerUser(tmpUser, simpleUserPb);
//                    cacheUser(updateUser);
//                    replaceList.add(updateUser);
//                } else {
//                    if (newVip != null) {
//                        //从非vip变vip
//                        vipChange = (newVip == true);
//                    }
//                    if (newWallet != null) {
//                        walletChange = (newWallet == true);
//                    }
//                    hasChange = true;
//                    tmpUser = UserHelper.createUserModelFromPB(simpleUserPb);
//                    tmpUser.setUpdateTime(System.currentTimeMillis());
//                    cacheUser(tmpUser);
//                    replaceList.add(tmpUser);
//                    //新加的用户
//                    avatarChange = !StringUtils.stringIsEqual(null, tmpUser.getAvatarUrl());
//                    oaVerifyChange = !StringUtils.stringIsEqual(null, tmpUser.getOaIcon());
//                    nameChange = !StringUtils.stringIsEqual(null, tmpUser.getNickName());
//                }
//                if (avatarChange)
//                    UserChangeNotifier.getInstance().notifyAvatarChange(userId, simpleUserPb.avatar);
//                if (vipChange)
//                    UserChangeNotifier.getInstance().notifyVipChange(userId, newVip);
//                if (oaVerifyChange)
//                    UserChangeNotifier.getInstance().notifyOAVerifyChange(userId, oaIcon);
//                if (ContactUtil.isOAAccount(userId) && nameChange) {//只有OA变更的时候才会发这个通知，user不用，因为user还要去contact表查数据
//                    UserChangeNotifier.getInstance().notifyNameChange(userId);
//                }
//                if (walletChange) {
//                    UserChangeNotifier.getInstance().notifyWalletChange(userId, newWallet);
//                }
//            }
//        }
//        if (!replaceList.isEmpty())
//            super.replaceUsers(replaceList, callBack);
//        UserFTSHelper.indexUser(replaceList);
//        return replaceList;
//    }

    private boolean hasChange(UserModel oldModel, UserModel newModel) {
        if (!StringUtils.stringIsEqual(oldModel.getNickName(), newModel.getNickName())
                || !StringUtils.stringIsEqual(oldModel.getNote(),
                newModel.getNote())
                || !StringUtils.stringIsEqual(oldModel.getAvatarPrevUrl(),
                newModel.getAvatarPrevUrl())
                || !StringUtils.stringIsEqual(oldModel.getAvatarUrl(),
                newModel.getAvatarUrl())
                || !StringUtils.stringIsEqual(oldModel.getCountry(),
                newModel.getCountry())
                || !StringUtils.stringIsEqual(oldModel.getCountryPhone(),
                newModel.getCountryPhone())
                || oldModel.getStatus_type() != newModel.getStatus_type()) {
            return true;
        }
        return false;
    }


    @Override
    public void saveUserLocal(UserModel user) {
        IDatabaseManager mainDB = StorageSdk.getMainDB();
        if (null == mainDB || user == null) {
            return;
        }
        VLog.i(TAG, "saveUserLocal for:%d", user.getUserId());
        synchronized (this) {
            cacheUser(user);
            super.replaceUser(user);
        }
    }

    @Override
    public boolean isLoaded() {
        return DaoLoadHelper.userDaoLoadFinish;
    }

    @Override
    public boolean isAppUser(long uid) {
        if (isSystemId(uid) || uid == LoginedUserMgr.getUserId()) {
            return true;
        }
        UserModel user = null;
        synchronized (this) {
            user = cachedUserMap.get(uid);
            if (null != user) {
                return true;
            }
        }
        if (!DaoLoadHelper.userDaoLoadFinish) {
            user = super.getUser(uid);
        }
        if (null != user) {
            return true;
        }
        return false;
    }


    @Override
    public void deleteAppUser(List<Long> uids) {
        VLog.i(TAG, "deleteBaba %s", uids);
        synchronized (this) {
            if (null == uids) {
                return;
            } else {
                for (long uid : uids) {

                    if (cachedUserMap.containsKey(uid)) {
                        cachedUserMap.remove(uid);
                    }
                }
                super.deleteAppUser(uids);
            }
        }
        UserFTSHelper.deleteUserIndex(ValueSafeTransfer.transformList(uids, (position, uid) -> String.valueOf(uid)));
    }

    @Override
    public void deleteAppUser(long uid) {
        VLog.i(TAG, "deleteBaba %d", uid);
        synchronized (this) {
            if (cachedUserMap.containsKey(uid)) {
                cachedUserMap.remove(uid);
            }
            super.deleteAppUser(uid);
        }
        UserFTSHelper.deleteUserIndex(String.valueOf(uid));
    }

    @Override
    public void saveFromMessage(UserModel user, boolean isVoip) {//改到外层去判断数据变更
        VLog.i(TAG, "saveFromMessage %d", user.getUserId());
        synchronized (this) {
            cacheUser(user);
            super.saveFromMessage(user, isVoip);
        }
        UserFTSHelper.indexUser(user);
    }


    public boolean isMatchEnd() {
        return isMatchEnd;
    }

    @Override
    public void setIsMatchEnd() {
        if (!isMatchEnd) {
            isMatchEnd = true;
            UserBroadcastUtils.sendUserModelChangeIntent(UserBroadcastUtils.kDAOCategory_RowReplace, null);
        }
    }

}
